package com.example.wendao.view.ui.fragment;

import android.app.AlertDialog;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wendao.App;
import com.example.wendao.R;
import com.example.wendao.model.entity.News;
import com.example.wendao.model.entity.User;
import com.example.wendao.model.service.UserService;
import com.example.wendao.viewmodel.UserViewModel;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegisterFragment extends Fragment {

    public Button back_to_login;
    public EditText username;
    public EditText password;
    public EditText check_password;

    public EditText birthday;
    public boolean bir;

    public RadioGroup gender;
    public RadioButton male;
    public RadioButton female;
    public Button btn_register;

    public Boolean un_ok;//用户名是否合格
    public Boolean pw_ok;//密码是否合格
    public int gender_out;//性别是否为空

    public User user;

    private UserViewModel userViewModel;

    public RegisterFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        userViewModel = new ViewModelProvider(App.getInstance()).get(UserViewModel.class);
        View view = inflater.inflate(R.layout.fragment_register, container, false);
        back_to_login = view.findViewById(R.id.back_to_login);
        username = view.findViewById(R.id.username);
        password = view.findViewById(R.id.password);
        check_password = view.findViewById(R.id.check_password);
        gender = view.findViewById(R.id.gender);
        male = view.findViewById(R.id.male);
        female = view.findViewById(R.id.female);
        btn_register = view.findViewById(R.id. btn_register);
        birthday = view.findViewById(R.id.birthday);
        user = new User();

        back_to_login.setOnClickListener(view1 -> Navigation.findNavController(view).navigate(R.id.action_registerFragment_to_loginFragment));

        btn_register.setOnClickListener(view12 -> {
            //用户名验证
            un_ok = false;
            if (username.getText().toString().trim().equals("")) {
                Toast.makeText(getActivity(), "用户名不能为空哦~", Toast.LENGTH_SHORT).show();
            } else if (username.length() < 4 || username.length() > 13) {
                Toast.makeText(getActivity(), "请填写一个符合要求的用户名！", Toast.LENGTH_SHORT).show();
            } else if (userViewModel.checkUsername(username.getText().toString().trim())) {
                Toast.makeText(getActivity(), "用户名已存在，请换一个吧！", Toast.LENGTH_SHORT).show();
            } else un_ok = true;

            //密码验证
            pw_ok = false;
            if (password.getText().toString().trim().equals("")) {
                Toast.makeText(getActivity(), "密码不能为空哦~", Toast.LENGTH_SHORT).show();
            } else if (password.getText().toString().length() < 6 || password.getText().toString().length() > 8) {
                Toast.makeText(getActivity(), "请填写一个符合要求的密码！", Toast.LENGTH_SHORT).show();
            } else if (!password.getText().toString().equals(check_password.getText().toString())) {
                Toast.makeText(getActivity(), "密码与确认密码不相符", Toast.LENGTH_SHORT).show();
            } else pw_ok = true;

            //生日验证
            bir = false;
            if (birthday.getText().toString().trim().equals("")) {
                Toast.makeText(getActivity(), "生日不能为空哦~", Toast.LENGTH_SHORT).show();
            } else {
                String regex = "^(19|20)\\d{2}-(1[0-2]|0?[1-9])-(0?[1-9]|[1-2][0-9]|3[0-1])$";
                Pattern pattern = Pattern.compile(regex);
                Matcher m = pattern.matcher(birthday.getText().toString().trim());
                boolean dateFlag = m.matches();
                if (!dateFlag) {
                    Toast.makeText(getActivity(), "日期格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }
                DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                formatter.setLenient(false);
                try {
                    formatter.parse(birthday.getText().toString().trim());
                    bir = true;
                } catch (Exception e) {
                    Toast.makeText(getActivity(), "日期格式错误", Toast.LENGTH_SHORT).show();
                }
            }

            //性别验证
            gender_out = 0;
            if (gender.getCheckedRadioButtonId() == R.id.male) {
                gender_out = 1;
            } else if (gender.getCheckedRadioButtonId() == R.id.female) {
                gender_out = 2;
            } else Toast.makeText(getActivity(), "性别选项不能为空哦", Toast.LENGTH_SHORT).show();

            if (un_ok && pw_ok && gender_out != 0 && bir) {
                user.setUsername(username.getText().toString().trim());
                user.setPassword(password.getText().toString().trim());
                user.setBirthday(birthday.getText().toString().trim());
                if (gender_out == 1)
                    user.setGender(false);  //  男性标记为false
                else if (gender_out == 2)
                    user.setGender(true);   //  女性标记为true
                user.setCoins(0);
                user.setCoupons(0);
                user.setHead(null);
                user.setSigndays(0);
                userViewModel.register(user);
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("亲爱的闻道道友：");
                builder.setMessage("恭喜您已经注册成功啦，快去登录试试吧！");
                builder.setPositiveButton("确定", (dialogInterface, i) -> Navigation.findNavController(view).navigate(R.id.action_registerFragment_to_loginFragment));
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        });
        return view;
    }
}
